package com.study.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * netty客户端
 */
public class EchoClient {
    private final String host;
    private final int port;

    public EchoClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public static void main(String[] args) throws InterruptedException {
        new EchoClient("127.0.0.1", 9999).start();
    }

    public void start() throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup(); // 使用NIO线程组
        try {
            Bootstrap b = new Bootstrap(); // 客户端必备
            b.group(group) // 将线程组交给启动类
                    .channel(NioSocketChannel.class) // 指明使用NIO进行网络通讯 和上方的group要对应
                    .remoteAddress(host, port) // 配置远程服务器地址
                    .handler(new EchoClientHandler());
            ChannelFuture future = b.connect().sync(); // 连接远程节点 阻塞等待直到连接完成
            future.channel().closeFuture().sync(); // 阻塞直到channel关闭
        } finally {
            group.shutdownGracefully().sync();
        }
    }
}
